package com.example.commonlib.commonutil;

import android.app.Activity;
import android.text.TextUtils;

import com.example.commonlib.base.BaseActivity;

import java.util.LinkedList;

/**
 * Created by aiyou on 2017/3/14.
 */

public class ActivityManager {

    public static ActivityManager instance;
    private static LinkedList<BaseActivity> activityList;
    private static int activityCount;

    public static ActivityManager getInstance(){
        if (instance == null)
            instance = new ActivityManager();
        return instance;
    }


    private ActivityManager(){
        activityList = new LinkedList<>();
    }


    public static LinkedList<BaseActivity> getActivityList() {
        return activityList;
    }

    public static int decreaseCount() {
        return activityCount--;
    }

    public static void increaseCount() {
        activityCount++;
    }

    /**
     * 当退出应用程序时调用该方法，finish全部Activity
     */
    public  void exit() {

        removeAllActivity();

        System.exit(0);


    }

    /**
     * 关闭除了参数的Activity
     * @param baseActivity
     */
    public void removeAllActivityExceptOne(BaseActivity baseActivity){
        for (BaseActivity activity : activityList) {
            if (activity != null && activity != baseActivity) {
                activity.finish();
            }
        }
    }


    public void removeActicityUseClassName(String cls){
        for (BaseActivity activity : activityList) {
            if (activity != null && TextUtils.equals(activity.getComponentName().getClassName(),cls)) {
                activity.finish();
            }
        }
    }
    public void removeActicityUseClassName2(String cls){
        for (BaseActivity activity : activityList) {
            if (activity != null && !TextUtils.equals(activity.getComponentName().getClassName(),cls)) {
                activity.finish();
            }
        }
    }


    public Activity getActivityUseClassName(String cls){
        for (BaseActivity activity : activityList) {
            if (activity != null && TextUtils.equals(activity.getComponentName().getClassName(),cls)) {
               return activity;
            }
        }
        return null;
    }


    public  void removeAllActivity(){
        for (BaseActivity activity : activityList) {
            if (activity != null) {
                activity.finish();
            }
        }

        activityList.clear();
        activityList = null;
    }

    /**
     * 每打开一个activity都加入list方便统一管理
     *
     * @param activity
     */
    public void addActivity(BaseActivity activity) {
        if (activity != null && !activityList.contains(activity)) {
            activityList.add(activity);
        }
    }


    /**
     * 每关闭一个页面退出栈
     * @param activity
     */
    public void removeActivity(Activity activity){
        if (activity != null) {
            if (activityList.contains(activity)){
                activityList.remove(activity);
            }
        }
    }

}
